package com.jason.lucene.example.search;

import com.jason.lucene.example.LuceneInActionSampleData;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.core.SimpleAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.junit.Before;

import java.util.Map;

/**
 * @author he peng
 * @create 2017/12/4 14:29
 * @see
 */
public class BaseSearchingTest {

    protected Directory indexDir;


    @Before
    public void setUp() throws Exception {
//        this.indexDir = FSDirectory.open(Paths.get("C://lucene//index"));
        this.indexDir = new RAMDirectory();
        addDocument(this.indexDir);
    }

    protected void addDocument(Directory indexDir) throws Exception {
        IndexWriterConfig conf = new IndexWriterConfig(getAnalyzer());
        IndexWriter indexWriter = new IndexWriter(indexDir, conf);
        for (int i = 0; i < LuceneInActionSampleData.INIT_DATAS.size() ; i++ ) {
            Document doc = new Document();
            Map<String, String> dataMap = LuceneInActionSampleData.INIT_DATAS.get(i);
            for (Map.Entry<String, String> entry : dataMap.entrySet()) {
                doc.add(new Field(entry.getKey() , entry.getValue() , TextField.TYPE_STORED));
            }
            System.out.println("indexing doc ===> " + doc);
            indexWriter.addDocument(doc);
        }
        indexWriter.close();
    }

    protected Analyzer getAnalyzer() {
        return new SimpleAnalyzer();
    }

}
